package com.mai4j.maiadmin.validation.constraintvalidators;


import com.mai4j.maiadmin.support.JooqProvider;
import com.mai4j.maiadmin.validation.constraints.UniqAccount;
import org.apache.commons.lang3.StringUtils;
import org.jooq.DSLContext;
import org.jooq.tools.reflect.Reflect;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import static com.mai4j.maiadmin.generated.Tables.USER;


/**
 * Created by 席有芳 on 2021/12/5.
 *
 * @author 席有芳
 */
public class UniqAccountValidator implements ConstraintValidator<UniqAccount, Object> {
    /**
     * 字段
     */
    private String field;
    /**
     * message
     */
    private String message;

    @Override
    public void initialize(UniqAccount uniqAccount) {
        this.field = uniqAccount.field();
        this.message = uniqAccount.message();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        String account = Reflect.on(value).field(field).get();
        if (StringUtils.isBlank(account)) return true;
        DSLContext dsl = JooqProvider.dsl();
        // 账号和邮箱不能相同
        int count = dsl.fetchCount(dsl.selectFrom(USER).where(USER.ACCOUNT.eq(account).or(USER.EMAIL.eq(account))));
        boolean isValid = count == 0;
        if (!isValid) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate(message).addPropertyNode(field).addConstraintViolation();
        }
        return isValid;
    }
}
